import axios from "axios";

export function formatDate(cellValue) {
    if (cellValue === null || cellValue === '') return ''
    var date = new Date(cellValue)
    var year = date.getFullYear()
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
    var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
    var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
    return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}


export function getName(){
    return  addr2Name()

}

export async function addr2Name()  {
    try {
        const [provinceResponse, cityResponse] = await Promise.all([
            axios.get('/province_object.json'),
            axios.get('/city_object.json')
        ])

        const provinceObject = provinceResponse.data;
        const cityObject = cityResponse.data;

        let provinces = convertToProvinces(provinceObject);
        let allCities = convertToProvinces(cityObject);
        return {
            provinces: provinces,
            cities: allCities
        };
        //console.log(provinces)
        /*provinces.forEach(province => {
            if (id == province.provinceId) {
                //console.log(province)
                return province.label
            }
        })
        allCities.forEach(city => {
            if (id == city.provinceId) {
                return city.label
            }
        })*/
    } catch (error) {
        console.error('加载省市数据失败:', error);
    }
}

const convertToProvinces = (provinceObject) => {
    return Object.keys(provinceObject).map((provinceId, index) => ({
        value: index,
        label: provinceObject[provinceId].name,
        provinceId : provinceId
    }));
};

const convertToCities = (cityObject) => {
    const cities = {};
    Object.keys(cityObject).forEach((cityId,index) => {
        const city = cityObject[cityId];
        if (!cities[city.province]) {
            cities[city.province] = [];
        }
        cities[city.province].push({
            value: index,
            label: city.name,
            cityId : cityId,
        });
    });
    return cities;
};